﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Utilities
{
    public class SerializeUtils
    {

        /***********************************************************
         * 
         * class 要有  [Serializable]
         * 
         * **********************************************************/
        public static bool SaveToXML(String fileName, Object obj)
        {
            if (File.Exists(fileName))
                File.Delete(fileName);
            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(obj.GetType());
            Stream s = File.Open(fileName, FileMode.Create);
            ser.Serialize(s,obj);
            s.Close();
            return true;
        }
        public static object ReadFromXML(String fileName, Type type)
        {
            object result = null;
            if (File.Exists(fileName))
            {
                System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(type);
                Stream s = File.Open(fileName, FileMode.Open);
                result = ser.Deserialize(s);
                s.Close();
            }
            return result;
        }

        public static bool SaveToBin(String fileName, object obj)
        {
            try
            {
                if (File.Exists(fileName))
                    File.Delete(fileName);
                String path = Path.GetDirectoryName(fileName);
                if (Directory.Exists(path) == false)
                    Directory.CreateDirectory(path);

                using (Stream stream = File.Open(fileName, FileMode.Create))
                {
                    BinaryFormatter bin = new BinaryFormatter();
                    bin.Serialize(stream, obj);
                }
                return true;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                return false;
            }
        }
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        public static object LoadFromBin(String fileName)
        {
            if (File.Exists(fileName) == false)
                return null;

            object result = null;
            using (Stream stream = File.Open(fileName, FileMode.Open))
            {
                BinaryFormatter bin = new BinaryFormatter();

                result = bin.Deserialize(stream);
            }
            return result;

        }
    }
}

